from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.alert import Alert
from config.config import HOST
import pyautogui
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep


class BasePage(object):
    def __init__(self,driver):
        self.driver = driver
        self.url = '{}{}'.format(HOST,self.url)

    def open(self):
        """访问指定页面"""
        self.driver.get(self.url)

    def find_element(self,locater, timeout=5):
        """查找页面元素"""
        return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locater))

    def get_text(self,locater):
        """获取指定元素文本内容"""
        return self.find_element(locater).text

    def alert(self):
        """弹窗操作"""
        return Alert(self.driver)

    def click(self,locater):
        """点击所选元素"""
        self.find_element(locater).click()
        sleep(1)

    def send_keys(self,locater,text):
        """向指定元素输入文本"""
        self.find_element(locater).send_keys(text)

    def select(self,locater,index):
        """下拉框选择指定索引选项"""
        Select(self.find_element(locater)).select_by_index(index)

    @staticmethod
    def click_position(x, y):
        """点击指定坐标位置"""
        pyautogui.click(x,y)
        sleep(1)

    @staticmethod
    def sendkeys_position(text):
        """指定坐标输入文本"""
        pyautogui.press('capslock')
        pyautogui.write(text)


    def drag_and_drop(self, origin_el, destination_el):
        """
        传入两个元素的坐标，进行滑动(无惯性滑动)
        :param origin_el:滑动开始元素
        :param destination_el:滑动结束元素
        :return: None
        """
        mouse = ActionChains(self.driver)
        origin_point = self.find_element(origin_el)
        end_point = self.find_element(destination_el)
        mouse.drag_and_drop(origin_point, end_point).perform()